package com.example.flutteruikit;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

import android.os.Parcelable;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

public class MainActivity extends FlutterActivity {
	MethodChannel methodChannel;
	//NFC
	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;
	private IntentFilter[] intentFiltersArray;
	private String[][] techListsArray;

	EventChannel eventChannel;
	EventChannel.EventSink mEvents;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		GeneratedPluginRegistrant.registerWith(this);
		getWindow().addFlags(LayoutParams.FLAG_SECURE);
		eventChannel = new EventChannel(getFlutterView(), "nfc");
		eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
			@Override
			public void onListen(Object arguments, EventChannel.EventSink events) {
				mEvents = events;
			}

			@Override
			public void onCancel(Object arguments) {

			}
		});
		AndroidChannel();
	}

	@Override
	protected void onStart() {
		super.onStart();
		try {
			initNFC(this);
		} catch (IntentFilter.MalformedMimeTypeException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (nfcAdapter != null) {
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(this);
		}
	}

	/**
	 * 初始化NFC
	 */
	private void initNFC(Context context) throws IntentFilter.MalformedMimeTypeException {
		int requestCode = 0, flags = 0;
		Intent intent = new Intent(context, getClass());
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags);
		IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
		filter.addDataType("*/*");
		intentFiltersArray = new IntentFilter[]{filter};
		techListsArray = new String[][]{
				new String[]{NfcA.class.getName()},
				new String[]{NfcB.class.getName()},
				new String[]{NfcF.class.getName()},
				new String[]{NfcV.class.getName()},
				new String[]{Ndef.class.getName()},
				new String[]{NdefFormatable.class.getName()},
				new String[]{MifareClassic.class.getName()},
				new String[]{MifareUltralight.class.getName()},
				new String[]{IsoDep.class.getName()}};
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String action = intent.getAction();
		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
				|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
				|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
			Parcelable parcelable = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			String nfcId = byteToHex(((Tag) parcelable).getId());
			if (mEvents != null)
				mEvents.success(nfcId);
		}
	}

	private String byteToHex(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		StringBuilder hexStr = new StringBuilder();
		for (int i = bytes.length - 1; i >= 0; i--) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexStr.append(hex);
		}
		BigInteger bigInteger = new BigInteger(hexStr.toString(), 16);
		return bigInteger.toString();
	}

	public void AndroidChannel() {
		methodChannel = new MethodChannel(getFlutterView(), "com.sovell.android.channel");
		methodChannel.setMethodCallHandler(new MethodCallHandler() {
			@Override
			public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {

				if (call.method.equals("getMessage")) {
					if (call.arguments != null) {
						String key ="";
						Map<String, String> params = new HashMap<>();
						Map<String, String> mArguments =call.arguments();
						for (Map.Entry<String, String> entry : mArguments.entrySet()) {
							if(entry.getKey().equals("key")){
								key =entry.getValue();
							}else {
								params.put(entry.getKey(), entry.getValue());
							}
						}

						Map<String, String>  sigParams = ParamsUtil.getParams(params,key);
						result.success(sigParams);
					}else {
						result.error("3","没有参数",null);
					}
				}

			}
		});

	}
}
